
package com.core.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.b5m.b5mei.R;
import com.core.api.B5MBaseRequest;
import com.core.util.B5MToaster;
import com.core.util.FileUtils;
import com.core.util.ImageUtils;
import com.core.util.StringUtils;

public abstract class B5MBasePictureFragment extends B5MBaseFragment
{
    private PopupWindow pop;
    protected File sdcardTempFile;
    public static final int IMAGE_SIZE = 180;
    public static final int NONE = 110;
    public static final int PHOTOHRAPH = 111;// 拍照
    public static final int PHOTOZOOM = 112; // 缩放
    public static final int PHOTORESOULT = 113;// 结果
    public static final String IMAGE_UNSPECIFIED = "image/*";
    //
    private final static String FILE_SAVEPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mtalk/";
    private final static int CROP = 200;
    private Uri origUri;
    private Uri cropUri;
    private Bitmap protraitBitmap;
    //    private File sdcardTempFile;
    private String protraitPath;
    private String fileName = B5MBaseRequest.IMAGE_KEY;

    public void showPhotoPopupWindow(View v)
    {
        if (pop == null)
        {
            View view = View.inflate(mContext, R.layout.b5m_layout_camera_dialog, null);
            Button takePhoto_btn = (Button) view.findViewById(R.id.takePhoto_btn);// 拍照
            LinearLayout camera_pop_linear = (LinearLayout) view.findViewById(R.id.camera_pop_linear);
            Button pickPicutre = (Button) view.findViewById(R.id.pickPicutre);// 从相册取
            Button camera_cancel = (Button) view.findViewById(R.id.camera_cancel);// 取消
            camera_cancel.setOnClickListener(photoOnClickListener);
            takePhoto_btn.setOnClickListener(photoOnClickListener);
            pickPicutre.setOnClickListener(photoOnClickListener);
            camera_pop_linear.setOnClickListener(photoOnClickListener);
            pop = new PopupWindow(view, android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, false);
            pop.setAnimationStyle(R.style.AnimBottom);
        }
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }
    private OnClickListener photoOnClickListener = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            switch (v.getId())
            {
                case R.id.takePhoto_btn:
                    takePhotoOrNot(true);// 拍照
                    break;
                case R.id.pickPicutre:
                    takePhotoOrNot(false);
                    break;
                case R.id.camera_cancel:
                    pop.dismiss();
                    break;
                case R.id.camera_pop_linear:
                    pop.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    public void takePhotoOrNot(boolean flag)
    {
        if (pop != null && pop.isShowing())
        {
            pop.dismiss();
        }
        if (flag)
        {
            startActionCamera();
        }
        else
        {
            startImagePick();
        }
    }

    /**
     * 选择图片裁剪
     * 
     * @param output
     */
    private void startImagePick()
    {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "选择图片"), ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
    }

    /**
     * 相机拍照
     * 
     * @param output
     */
    private void startActionCamera()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
        startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
    }

    // 裁剪头像的绝对路
    private Uri getUploadTempFile(Uri uri)
    {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED))
        {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists())
            {
                savedir.mkdirs();
            }
        }
        else
        {
            B5MToaster.showShort(mActivity, "无法保存上传的头像，请检查SD卡是否挂载", 0);
            return null;
        }
        //        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);
        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath))
        {
            thePath = ImageUtils.getAbsoluteImagePath(getActivity(), uri);
        }
        String ext = FileUtils.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        //        String cropFileName = "osc_crop_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路
        protraitPath = FILE_SAVEPATH + fileName;
        sdcardTempFile = new File(protraitPath);
        cropUri = Uri.fromFile(sdcardTempFile);
        return this.cropUri;
    }

    // 拍照保存的绝对路
    private Uri getCameraTempFile()
    {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED))
        {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists())
            {
                savedir.mkdirs();
            }
        }
        else
        {
            B5MToaster.showShort(mActivity, "无法保存上传的头像，请检查SD卡是否挂载", 0);
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 照片命名
        String cropFileName = "osc_camera_" + timeStamp + ".jpg";
        // 裁剪头像的绝对路
        protraitPath = FILE_SAVEPATH + cropFileName;
        sdcardTempFile = new File(protraitPath);
        cropUri = Uri.fromFile(sdcardTempFile);
        this.origUri = this.cropUri;
        return this.cropUri;
    }

    @Override
    public void onActivityResult(int requestCode , int resultCode , Intent data)
    {
        if (resultCode != Activity.RESULT_OK)
            return;
        switch (requestCode)
        {
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
                startActionCrop(origUri);// 拍照后裁
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
                startActionCrop(data.getData());// 选图后裁
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
                uploadImageToServer();// 上传新照
                break;
        }
    }

    /**
     * 拍照后裁
     * 
     * @param data
     *            原始图片
     * @param output
     *            裁剪后图
     */
    private void startActionCrop(Uri data)
    {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑
        intent.putExtra("scaleUpIfNeeded", true);// 去黑
        startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    /**
     * 上传图片到服务端
     */
    public abstract void uploadImageToServer();

    @Override
    public int doGetContentViewId()
    {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void doInitSubViews(View containerView)
    {
        // TODO Auto-generated method stub
    }

    @Override
    public void doInitDataes()
    {
        // TODO Auto-generated method stub
    }

    @Override
    public void doAfter()
    {
        // TODO Auto-generated method stub
    }
}
